<template>
  <section>
    <van-sticky>
      <PageHeader title="实名认证"/>
    </van-sticky>

    <van-field label="姓名" v-model="member.name" placeholder="请输入姓名" />
    <van-field label="身份证号码" v-model="member.idcard" placeholder="请输入您的身份证号码" />

    <div class="pd10">
      <van-button type="primary" round block @click="onStartDetect">进入实名认证流程<span class="ml5" v-if="siteConfig">({{siteConfig.prices.faceid_detect}}元/人)</span></van-button>
    </div>
  </section>
</template>

<script>
  import Vue from 'vue';
  import {Uploader, Toast, Sticky, Button, Field} from 'vant';
  import {
    fileUploadByBase64Uri,
    memberAuthFaceDetectUrlUri,
    memberAuthFaceDetectResultUri,
    wechatJsApiConfigUri,
    serviceChargeOrderCreateUri,
    wxPayServiceChargeOrderPayTradeUri,
    wxPayQueryUri,
    memberRechargeRecordInfoUri, memberMyProfileUri
  } from "../../../common/api";
  import {STATIC_BASE_URL} from "../../../common/api";
  import PageHeader from "../../componets/PageHeader";
  import util from "../../../assets/js/util";
  import {
    IID_TYPE_FACEID_DETECT,
    IID_TYPE_UNLOCK_MEMBER_PHONE,
    MEMBER_RECHARGE_RECORD_IID_TYPE_FACEID_DETECT
  } from "../../../common/constants";

  Vue.use(Uploader).use(Toast).use(Sticky).use(Button).use(Field);

  let wxReady = false;

  export default {
    components: {
      PageHeader
    },
    data() {
      return {
        STATIC_BASE_URL: STATIC_BASE_URL,
        member: {
          name: '',
          idcard: ''
        },
        siteConfig: null
      }
    },
    methods: {
      onStartDetect() {
        if(this.member.name.length == 0 || this.member.idcard.length == 0) {
          Toast('请填写姓名和身份证号');
          return;
        }
        this.getRechargeRecord();
      },
      getFaceDetectUrl() {
        const that = this;
        const url = memberAuthFaceDetectUrlUri + '?url=' + encodeURIComponent(window.location.href + '&from=tCloud')
                  + '&name=' + encodeURIComponent(this.member.name) + '&idcard=' + this.member.idcard;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            window.location.href = data.url;
          }
        }, response => {
          // error callback
        })
      },
      getFaceDetectResult() {
        const that = this;
        this.$http.get(memberAuthFaceDetectResultUri).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            if(data.result) {
              that.getMyProfile();
              that.toast.success('认证成功');
            } else {
              that.toast('认证失败');
            }
          }
        }, response => {
          // error callback
        })
      },
      getJsApiConfig() {
        if(!isWxServiceEnable) {
          return;
        }
        const that = this;
        const url = wechatJsApiConfigUri + '?url=' + encodeURIComponent(window.location.href);
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: data.appId, // 必填，公众号的唯一标识
              timestamp: data.timestamp, // 必填，生成签名的时间戳
              nonceStr: data.nonceStr, // 必填，生成签名的随机串
              signature: data.signature,// 必填，签名
              jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
            });

            wx.ready(function () {
              wxReady = true;
              console.log('wx配置成功');
            });

            wx.error(function (res) {
              console.log('wx配置出错');
            });
          }
        }, response => {
          // error callback
        })
      },
      createFaceIdDetectOrder() {
        if(!this.GLOBAL.userInfo) {
          this.$router.push({name: 'UserLogin'});
          return;
        }
        const that = this;
        const fromuid = localStorage.getItem('fromuid') ? localStorage.getItem('fromuid') : 0;

        const url = serviceChargeOrderCreateUri + '?fromuid=' + fromuid + '&iid=0&iid_type=' + IID_TYPE_FACEID_DETECT;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            that.chooseWXPay(data.order_sn);
          }
        }, response => {
          // error callback
        })
      },
      chooseWXPay(orderSn) {
        const that = this;
        const url = wxPayServiceChargeOrderPayTradeUri + '?order_sn=' + orderSn;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            const payParams = JSON.parse(data.pay_params);
            wx.chooseWXPay({
              timestamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: function (res) {
                // 支付成功后的回调函数
                that.onPaied(orderSn, data.pay_trade_no);
              },
              fail: function (res) {
                that.toast('支付失败');
              }
            });
          }
        }, response => {
          // error callback
        });
      },
      onPaied(orderSn, payTradeNo) {
        const that = this;
        const url = wxPayQueryUri + '?pay_trade_no=' + payTradeNo;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            if(data.success == 1) {
              that.toast('购买成功');
              that.getRechargeRecord();
            } else {
              that.toast('支付出错，请重试或联系客服付款');
            }
          }
        }, response => {
          // error callback
        })
      },
      getRechargeRecord() {
        const that = this;
        const url = memberRechargeRecordInfoUri + '?iid=0&iid_type=' + MEMBER_RECHARGE_RECORD_IID_TYPE_FACEID_DETECT;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            if(data.record) {
              that.getFaceDetectUrl();
            } else {
              that.createFaceIdDetectOrder();
            }
          }
        }, response => {
          // error callback
        })
      },
      getMyProfile() {
        const that = this;
        this.$http.get(memberMyProfileUri).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast(msg);
          } else {
            that.GLOBAL.memberProfile = data.member;
            that.EventBus.$emit('OnMemberAuth', null);
            that.$router.replace({name: 'MyIndex'});
          }
        }, response => {
          // error callback
        })
      }
    },
    created: function () {
      let _href = window.location.href;
      if (isWxServiceEnable && _href.indexOf('?replace=1') <= -1) {
        window.location.replace(_href + '?replace=1')
      }

      if (_href.indexOf('from=tCloud') > -1) {
        //防止页面后退
        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', function () {
          history.pushState(null, null, document.URL);
        });
      }
    },
    mounted: function () {
      if(this.GLOBAL.memberProfile && this.GLOBAL.memberProfile.realname_auth_status == 1) {
        this.$router.back();
      }

      let _href = window.location.href;
      if (_href.indexOf('from=tCloud') > -1) {
        this.getFaceDetectResult();
      }

      if(this.GLOBAL.siteConfig) {
        this.siteConfig = this.GLOBAL.siteConfig;
      }
      this.EventBus.$on('OnSiteConfigLoaded', () => {
        this.siteConfig = this.GLOBAL.siteConfig;
      });

      this.EventBus.$on('OnUserLogined', () => {
        if(this.GLOBAL.memberProfile && this.GLOBAL.memberProfile.realname_auth_status == 1) {
          this.$router.back();
        }
      });

      this.getJsApiConfig();
    }
  }
</script>

<style scoped>

</style>
